package cn.vire.electric.simulation.netty.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.nio.charset.Charset;

/**
 *
 */

@Slf4j
public class NettyClient implements ApplicationRunner {

    private String nettyServerHost = "localhost";

    private int nettyServerPort = 9090;

    public static void main(String[] args) throws Exception {
        new NettyClient().run(null);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.run0();
    }

    private void run0() throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            /*
            1 Bootstrap类似于，ServerBootstrap除了它用于非服务器通道，例如客户端或无连接通道。
            2 如果仅指定一个EventLoopGroup，它将同时用作老板组和工人组。但是，老板工人不用于客户端。
            3 而不是NioServerSocketChannel,NioSocketChannel用于创建客户端Channel.
            4 请注意，我们childOption()在此处不使用与 with 不同的方法，ServerBootstrap因为客户端SocketChannel没有父级。
            5 我们应该调用connect()方法而不是bind()方法。
             */
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new JsonObjectDecoder(),
                            new StringEncoder(Charset.forName("UTF-8")),
                            new StringDecoder(Charset.forName("UTF-8")),
                            new SimpleChannelInboundHandler<String>() {

                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                    log.info("收到报文;[{}]", msg);

                                }

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    JSONObject jo = new JSONObject();
                                    jo.put("name", "zhangsan");
                                    jo.put("age", 18);
                                    ctx.writeAndFlush(jo.toJSONString() + "{");
                                    ctx.writeAndFlush(jo.toJSONString().substring(1));

                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    log.error("捕获exceptionCaught", cause);
                                    ctx.close();
                                }
                            }
                    );
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(nettyServerHost, nettyServerPort).sync();

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }


}
